package cn.xfyun.example.util;

import cn.xfyun.example.config.AppConfig;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Component
public class CreateContext {

    private final RedisTemplate<String, Object> redisTemplate;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public CreateContext(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public String collectQuestionsAndAnswers(String interviewId, String fileid) throws JsonProcessingException {
        Map<String, String> result = new LinkedHashMap<>();

        try {
            // 1. 插入语言模型提示信息（放在最前面）
                result.put("prompt", "你是面试官，请根据下面的summary简历总结，question面试问题的类型、内容和分值,answer用户回答，综合问题的类型、分支来综合分析该用户面试结果");

            // 2. 从 Redis 获取 summary 数据
            String summaryKey = "file:" + fileid + ":summary";
            Object summary = redisTemplate.opsForValue().get(summaryKey);

            if (summary != null) {
                // 4. 添加到 result
                result.put("summary", summary.toString());
            } else {
                result.put("summary", "No summary found in Redis");
            }

            // 5. 原有逻辑（问题与答案收集）
            String totalKey = "interview:" + interviewId + ":question";
            Object totalObj = redisTemplate.opsForValue().get(totalKey);

            if (totalObj == null) {
                return "{}";
            }

            int totalQuestions;
            try {
                totalQuestions = Integer.parseInt(totalObj.toString());
            } catch (NumberFormatException e) {
                return "{}";
            }

            for (int i = 1; i <= totalQuestions; i++) {
                String answerKey = "interview:" + interviewId + ":answer:" + i;
                Object answerValue = redisTemplate.opsForValue().get(answerKey);
                String answerContent = (answerValue != null) ? answerValue.toString() : "用户未回答";
                String questionContent = null;

                try {
                    String fileKey = "file:" + fileid + ":question:" + i;

                    // 获取 HASH 中的 type 和 context 字段
                    Object typeObj = redisTemplate.opsForHash().get(fileKey, "type");
                    Object contextObj = redisTemplate.opsForHash().get(fileKey, "context");
                    Object scoreObj = redisTemplate.opsForHash().get(fileKey, "score");

                    String type = (typeObj != null) ? typeObj.toString() : null;
                    String context = (contextObj != null) ? contextObj.toString() : null;
                    String score = (scoreObj != null) ? scoreObj.toString() : null;

                    if (type != null && context != null) {
                        String combined = type + "，类型：" + context + "，分值：" + score;
                        result.put("question"+ i, combined);
                    } else {
                        // 可选：添加日志或默认值
                        result.put("context" + i, "No type or context found");
                    }
                } catch (Exception e) {
                    // 忽略异常
                }

                if (answerContent != null || questionContent != null) {
                    result.put("answer" + i, answerContent);
                }
            }


            // 6. 返回最终 JSON
            System.out.println("Result: " + result);
            return objectMapper.writeValueAsString(result);

        } catch (Exception e) {
            System.err.println("Error during Redis or JSON processing: " + e.getMessage());
            return result.isEmpty() ? "{}" : objectMapper.writeValueAsString(result);
        }
    }
}
